<template>
  <div class="login-container">
    <div class="login-left">
      <h1 class="system-title">交通违法识别管理系统</h1>
      <p class="system-desc">智能识别 · 高效处理 · 实时预警</p>
    </div>
    <div class="login-right">
      <el-card class="login-box">
        <h2 class="login-title">用户登录</h2>
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码" prefix-icon="Lock" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin" class="login-btn">登录</el-button>
          </el-form-item>
          <div class="login-options">
            <router-link to="/register" class="register-link">注册账号</router-link>
            <a href="#" class="forget-link">忘记密码？</a>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { login } from '@/api/auth'
import { ElMessage } from 'element-plus' // 添加导入

const router = useRouter()
const userStore = useUserStore()

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

const loginFormRef = ref()

const handleLogin = async () => {
  // 在handleLogin函数的try块末尾添加
  try {
    await loginFormRef.value.validate()
    const response = await login(loginForm)
    
    console.log('登录响应完整数据:', JSON.stringify(response))
    
    // 提取token和用户信息
    const token = response.data?.token || response.token || response.data?.data?.token
    let userData = response.data || response
    
    // 确保userData包含role字段
    if (!userData.role && userData.data && userData.data.role) {
      userData = userData.data
    }
    
    // 确保role字段是字符串类型
    if (userData.role !== undefined && userData.role !== null) {
      userData.role = String(userData.role)
    }
    
    console.log('处理后的用户数据:', JSON.stringify(userData))
    
    if (!token) {
      throw new Error('后端返回数据格式异常，缺少token字段')
    }
    
    // 直接保存token到localStorage
    localStorage.setItem('token', token)
    localStorage.setItem('userInfo', JSON.stringify(userData))
    
    // 同时更新store
    userStore.setToken(token)
    userStore.setUserInfo(userData)
    
    console.log('登录成功，用户角色:', userData.role, '保存的token:', token)
    
    // 根据用户角色跳转到不同页面
    // 检查localStorage中保存的用户信息
    setTimeout(() => {
      const savedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      console.log('保存在localStorage中的用户信息:', savedUserInfo)
      console.log('用户角色类型:', typeof savedUserInfo.role)
    }, 100)
    
    router.push('/home')
  } catch (err) {
    console.error('登录错误详情:', err)
    ElMessage.error(err.message || '登录失败')
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100vh;
  background: url('@/assets/login-bg.jpg') no-repeat center center;
  background-size: cover;
  padding: 0 10%;
}

.login-left {
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.system-title {
  font-size: 2.5em;
  margin-bottom: 20px;
}

.system-desc {
  font-size: 1.2em;
  opacity: 0.9;
}

.login-right {
  width: 400px;
}

.login-box {
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.95);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 1.5em;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  font-size: 14px;
}

.register-link, .forget-link {
  color: #409EFF;
  text-decoration: none;
}

.register-link:hover, .forget-link:hover {
  color: #66b1ff;
}
</style>